import {Component, Hook, Mut, VueComponent, Link, ComponentProps} from 'vue3-oop'
import {DialogReactive, NButton, NCard, NForm, NFormItem, NInput, NSpace, NTable, NTag, PaginationProps} from 'naive-ui'
import styles from './index.module.scss'

import DefinitionApi from './DefinitionApi'
import DynaTablePanel from "@/components/panel/DynaTablePanel2";
import WrokflowApi from "@/module/main/workflow/DefinitionListView/DefinitionApi";

interface IProps {
  maxWidth?:number,
  maxHeight?:number
}
@Component()
export default class Index extends VueComponent<IProps> {
  static defaultProps: ComponentProps<IProps> = {
    maxWidth:{default:800},
    maxHeight:{default:600}
  }

  constructor() {
    super()
  }

  @Mut() state = {
    columns: [
      // {
      //   key: "id",
      //   title: "ID"
      // },
      {
        key: "key",
        title: "流程标识"
      },{
        key: "name",
        title: "流程名称"
      },{
        key: "version",
        title: "最新版"
      },
      // {
      //   key: "deploymentId",
      //   title: "部署ID"
      // },
      // {
      //   key: "derivedVersion",
      //   title: "派生"
      // },
      {
        key: "tenantId",
        title: "租户ID"
      },
      // {
      //   key: "suspended",
      //   title: "挂起状态",
      //   render: (row:any)=>(row['suspended']===true?"是":"否")
      // },
      // {
      //   key: "isDeleted",
      //   title: "已删除",
      //   render: (row:any)=>(row['isDeleted']===true?"是":"否")
      // },
      {
        key: "SYS_ROW_ACTIONS",
        title: "操作",
        render: (row:any)=>(<NSpace size="small">
          <NButton onClick={()=>{this.openStartDialog(row);}}>启动</NButton>
          <NButton onClick={()=>{window.$router.push(`/main/workflow/design/${row.deploymentId}`);}}>编辑</NButton>
          {/*{!row['suspended']&&<NButton onClick={()=>{this.suspendDefinition(row);}}>挂起</NButton>}*/}
          {/*{row['suspended']&&<NButton onClick={()=>{this.activateDefinition(row);}}>激活</NButton>}*/}
        </NSpace>)
      }
    ] as any[],
    records: [] as any[]
  }

  private rowKey=(row:any)=>row.id;

  @Mut() pagination = {
    showSizePicker: true,
    pageSizes: [10,20,50,100],
    pageSize: 10,
    page: 1,
    itemCount: 0,
    showQuickJumper: true,
    onUpdatePage: (page:number) => {// 切换页
      this.pagination.page = page;
      this.triggerSearch();
    },
    onUpdatePageSize: (size:number) => {// 切换页大小
      this.pagination.pageSize = size;
      this.pagination.page = 1;
      this.triggerSearch();
    },
    prefix: ()=>(
      <NSpace>
        <NTag >总共 {this.pagination.itemCount} 项</NTag>
      </NSpace>
    )
  } as PaginationProps;

  // 快速搜索
  private handleQuickSearch=(value:string)=>{
    console.log("handleQuickSearch",value);
    this.triggerSearch();
  }

  // 触发查询
  triggerSearch=()=>{
    DefinitionApi.page({
      params:{},
      page:{size:this.pagination.pageSize,current:this.pagination.page}
    }).then(({data})=>{
      const { page,record } = data;
      this.pagination.itemCount = page.total;
      this.state.records = record;
    })
  }

  // 打开启动流程对话框
  private openStartDialog=(row:any)=>{
    const { id,name,version } = row;
    const formData = ref({
      instanceName:"",
      businessKey:"",
      startUserId:"",
      variables:[] as {
        id:string,
        name:string,
        value:string,
        required:boolean,
        defined:boolean
      }[]}).value;

    window.$http.get(`/api/workflow/definition/fields/${id}`).then(({data:result})=>{
      if(result.success){
        result.record.forEach((field:any)=>{
          formData.variables.push({id:field.id,name:field.name,value:field.value||'',required:field.required,defined:true})
        });
      }
    })

    const hendleStart=()=>{
      const variables = {} as any;
      formData.variables.forEach((item)=>{
        if(item.id && item.id.length>0){
          variables[item.id]=item.value;
        }
      });
      WrokflowApi.start({
        params:{
          definitionId: id,
          processInstanceName: formData.instanceName,
          businessKey: formData.businessKey,
          startUserId: formData.startUserId,
          variables: variables
        }
      }).then(({data})=>{
        if(data.success){
          window.$message.success(data.message);
        }
      })
    }

    const dialog = window.$popUp({
      style: {width:"600px",height:"600px"},
      content:()=>(
        <NCard title={`发起流程 ${name} [V${version}]`}>
          {{
            default:()=>(
              <NForm labelPlacement={"left"}>
                <NFormItem label='流程标题' required={true}><NInput value={formData.instanceName} onUpdateValue={(value)=>{formData.instanceName=value}} /></NFormItem>
                <NFormItem label='业务主键' required={true}><NInput value={formData.businessKey} onUpdateValue={(value)=>{formData.businessKey=value}} /></NFormItem>
                <NFormItem label='发起用户ID' required={true}><NInput value={formData.startUserId} onUpdateValue={(value)=>{formData.startUserId=value}} /></NFormItem>
                <NTable size='small'>
                  <thead><tr><th>参数名</th><th>参数值</th><th>操作</th></tr></thead>
                  <tbody>
                  {formData.variables.map((item:any,index)=>{
                    return <tr>
                      <td>
                        { item.defined && <NInput disabled value={item.name} class={styles.clear_disabled_color}/> }
                        { !item.defined && <NInput value={item.id} onUpdateValue={(value)=>{item.id=value}} /> }
                      </td>
                      <td><NInput value={item.value} onUpdateValue={(value)=>{item.value=value}} status={item.required && item.value.length===0?"warning":"success"} /></td>
                      <td>
                        { !item.defined && <NButton onClick={()=>{formData.variables.splice(index,1)}}>删除</NButton> }
                      </td>
                    </tr>
                  })}
                  </tbody>
                </NTable>
              </NForm>
            ),
            footer:()=>(<NSpace>
              <NButton size={"small"} onClick={()=>{formData.variables.push({id:"",name:"",value:"",required:false,defined:false})}}>添加</NButton>
              <NButton size={"small"} onClick={()=>{hendleStart();dialog.destroy();}}>确定</NButton>
              <NButton size={"small"} onClick={()=>{dialog.destroy()}}>取消</NButton>
            </NSpace>)
          }}
        </NCard>
      )
    }) as DialogReactive;
  }

  /**
   * 流程定义挂起
   */
  private suspendDefinition=(row:any)=>{
    window.$dialog.warning({
      title: "请注意！",
      content: `是否挂起流程定义“${row.name}[${row.key}] V${row.version}”？`,
      positiveText: "确定",
      onPositiveClick: ()=>{
        DefinitionApi.suspend({definitionId:row.id}).then(({data})=>{
          if(data.success){
            window.$message.success("流程定义挂起成功")
          }
          this.triggerSearch();
        })
      },
      negativeText:"取消",
      onNegativeClick: ()=>{}
    })
  }

  /**
   * 流程定义激活
   */
  private activateDefinition=(row:any)=>{
    window.$dialog.warning({
      title: "请注意！",
      content: `是否激活流程定义“${row.name}[${row.key}] V${row.version}”？`,
      positiveText: "确定",
      onPositiveClick: ()=>{
        DefinitionApi.activate({definitionId:row.id}).then(({data})=>{
          if(data.success){
            window.$message.success("流程定义激活成功")
          }
          this.triggerSearch();
        })
      },
      negativeText:"取消",
      onNegativeClick: ()=>{}
    })
  }

  /** 部署流程定义 */
  private handleDeployDefinition=()=>{
    const input = document.createElement('input');
    input.value = '选择文件';
    input.type = 'file';
    input.accept = 'application/xml';
    input.onchange = (event:any) => {
      let file = event.target.files[0];
      const form = new FormData();
      form.append("file", file);
      DefinitionApi.deploy(form).then(({data})=>{
        if(data.success){
          window.$message.success(data.message);
          this.triggerSearch();
        }
      })
    };
    input.click();
  }

  @Hook('Mounted')
  onMounted(){
    this.triggerSearch();
  }

  render() {

    return (
      <DynaTablePanel
        class={[styles.definition_list_view]}
        icon={"DocumentFlowchart20Filled"}
        title={"流程定义"}
        showQuickSearch={true}
        showSeniorSearch={true}
        onQuickSearch={this.handleQuickSearch}
        nDataTableProps={{
          rowKey:this.rowKey,
          columns:this.state.columns,
          data:this.state.records,
          pagination:this.pagination,
          maxHeight:this.props.maxHeight as number - 155
        }}
        toolbarActions={[
          // {
          //   name:"部署",
          //   needCheck:false,
          //   inMore:false,
          //   onClick:this.handleDeployDefinition
          // },
          {
            name:"新建流程",
            needCheck:false,
            inMore:false,
            onClick:()=>{window.$router.push("/main/workflow/design/new");}
          }
        ]}
      />
    )
  }
}
